<!--
 * @Descripttion: 编辑自提点
 * @Author: xiao li
 * @Date: 2020-07-06 12:17:07
 * @LastEditors: xiao li
 * @LastEditTime: 2022-01-11 15:04:59
-->
<template>
  <div class="lb-edit-card">
    <top-nav :title="navTitle" :isBack="true"></top-nav>
    <div class="page-main">
      <el-form
        @submit.native.prevent
        :model="subForm"
        :rules="subFormRules"
        ref="aForm"
        label-width="140px"
        class="basic-form"
      >
        <el-form-item label="自提点名称" prop="title">
          <el-input
            v-model="subForm.title"
            maxlength="40"
            placeholder="请输入自提点名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="所属公司" prop="public_company">
          <el-radio-group v-model="subForm.public_company">
            <el-radio :label="1">{{ $t('action.OFF') }}</el-radio>
            <el-radio :label="0">{{ $t('action.ON') }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="选择公司"
          prop="company"
          v-if="subForm.public_company === 0"
        >
          <el-cascader
            collapse-tags
            v-model="subForm.company"
            :options="options.company"
            :props="{
              multiple: true,
              checkStrictly: true,
              label: 'name',
              value: 'id'
            }"
            clearable
          ></el-cascader>
        </el-form-item>
        <el-form
          @submit.native.prevent
          :model="areaForm"
          :rules="areaFormRules"
          ref="bForm"
          label-width="140px"
          class="basic-form"
        >
          <el-form-item label="自提地址" prop="selectedOptions">
            <el-cascader
              size="large"
              :options="areaOptions"
              v-model="areaForm.selectedOptions"
              @change="handleChange"
              placeholder="请选择自提地址"
              :props="{ checkStrictly: true }"
              clearable
            ></el-cascader>
          </el-form-item>
        </el-form>
        <el-form-item label="详细地址" prop="address">
          <el-input
            type="textarea"
            :rows="4"
            v-model="subForm.address"
            maxlength="60"
            resize="none"
            show-word-limit
            placeholder="请输入自提点的详细地址，最短5个字"
          ></el-input>
        </el-form-item>
        <el-form
          @submit.native.prevent
          :model="subForm"
          :rules="subFormRules"
          ref="cForm"
          :inline="true"
          label-width="100px"
          class="inline-form"
        >
          <el-form-item label="自提点经度" prop="longitude">
            <el-input
              v-model="subForm.longitude"
              placeholder="请输入自提点经度"
            ></el-input>
          </el-form-item>
          <el-form-item label="自提点纬度" prop="latitude">
            <el-input
              v-model="subForm.latitude"
              placeholder="请输入自提点纬度"
            ></el-input>
          </el-form-item>
          <lb-button
            type="primary"
            class="getLocation"
            size="mini"
            plain
            @click="showMap = true"
            >获取自提点坐标</lb-button
          >
        </el-form>

        <el-form
          @submit.native.prevent
          :model="phoneForm"
          :rules="phoneFormRules"
          ref="dForm"
          label-width="140px"
          class="basic-form"
        >
          <el-form-item label="联系电话" prop="phone">
            <el-input
              v-model="phoneForm.phoneCode"
              maxlength="10"
              placeholder="区号"
              style="width: 60px"
            ></el-input>
            -
            <el-input
              v-model="phoneForm.phone"
              maxlength="20"
              placeholder="请输入准确的电话号码，便于买家联系商家"
              style="width: 322px"
            ></el-input>
          </el-form-item>
        </el-form>

        <el-form-item label="接待时间" prop="reception_time">
          <el-radio-group v-model="subForm.reception_time">
            <el-radio :label="0">全天</el-radio>
            <el-radio :label="1">自定义时间</el-radio>
          </el-radio-group>
          <lb-tool-tips>{{
            subForm.reception_time === 0
              ? '勾选全天，默认每天的0-24点都可以提货'
              : '勾选自定义时间，将会按照所输入的日期时间进行周期性重复'
          }}</lb-tool-tips>
        </el-form-item>

        <el-form
          @submit.native.prevent
          :model="subForm"
          :rules="subFormRules"
          label-width="140px"
          class="basic-form"
          v-if="subForm.reception_time === 1"
        >
          <el-form-item label>
            <el-checkbox-group v-model="checkList" @change="changeCheckBox">
              <div
                v-for="(item, index) in authList"
                :key="index"
                :style="{
                  display: 'inline-block',
                  marginLeft: index === 0 ? 0 : '15px'
                }"
              >
                <el-checkbox :label="item.title"></el-checkbox>
                <lb-tool-tips v-if="item.tips">{{ item.tips }}</lb-tool-tips>
              </div>
            </el-checkbox-group>
          </el-form-item>
          <div v-if="subForm.work === 1">
            <el-form-item label>
              <div class="flex-warp">
                <div class="mr-md" style="width: auto">周一至周五</div>
                <el-time-select
                  placeholder="开始时间"
                  v-model="subForm.work_start_time"
                  :picker-options="{
                    start: '00:00',
                    step: '00:05',
                    end: '24:00'
                  }"
                  style="width: 150px"
                ></el-time-select>
                <div class="ml-md mr-md" style="width: auto">至</div>
                <el-time-select
                  placeholder="结束时间"
                  v-model="subForm.work_end_time"
                  :picker-options="{
                    start: '00:00',
                    step: '00:05',
                    end: '24:00',
                    minTime: subForm.work_start_time
                  }"
                  style="width: 150px"
                ></el-time-select>
                <div style="width: 20px"></div>
                <lb-button
                  type="danger"
                  @click="
                    ;(subForm.work_start_time = ''),
                      (subForm.work_end_time = '')
                  "
                  >{{ $t('action.reset') }}</lb-button
                >
              </div>
            </el-form-item>
          </div>
          <div v-if="subForm.no_work === 1">
            <el-form-item label>
              <div class="flex-warp">
                <div class="mr-md" style="width: auto">周六至周日</div>
                <el-time-select
                  placeholder="开始时间"
                  v-model="subForm.no_work_start_time"
                  format="timestamp"
                  :picker-options="{
                    start: '00:00',
                    step: '00:05',
                    end: '24:00'
                  }"
                  style="width: 150px"
                ></el-time-select>
                <div class="ml-md mr-md" style="width: auto">至</div>
                <el-time-select
                  placeholder="结束时间"
                  v-model="subForm.no_work_end_time"
                  format="timestamp"
                  :picker-options="{
                    start: '00:00',
                    step: '00:05',
                    end: '24:00',
                    minTime: subForm.no_work_start_time
                  }"
                  style="width: 150px"
                ></el-time-select>
                <div style="width: 20px"></div>
                <lb-button
                  type="danger"
                  @click="
                    ;(subForm.no_work_start_time = ''),
                      (subForm.no_work_end_time = '')
                  "
                  >{{ $t('action.reset') }}</lb-button
                >
              </div>
            </el-form-item>
          </div>
        </el-form>
        <el-form-item label="自提时间" prop="is_self">
          <el-radio-group v-model="subForm.is_self">
            <el-radio :label="0">无需买家选择自提时间</el-radio>
            <el-radio :label="1">需要买家选择自提时间</el-radio>
          </el-radio-group>
          <lb-tool-tips>{{
            subForm.is_self === 1
              ? '买家下单选择上门自提，必须选择自提时间，卖家需要按约定时间备货'
              : '将会提示买家尽快到店自提'
          }}</lb-tool-tips>
        </el-form-item>
        <div v-if="subForm.is_self === 1">
          <el-form-item label="细分时段" prop="time_slot">
            <el-radio-group v-model="subForm.time_slot">
              <el-radio :label="0">半小时</el-radio>
              <el-radio :label="1">一小时</el-radio>
            </el-radio-group>
            <lb-tool-tips mode="text"
              ><div class="flex-y-center" style="cursor: pointer">
                买家可选的自提时间会根据时段进行细分。
                <div @click="showDialog = true" class="c-link">查看示例</div>
              </div>
            </lb-tool-tips>
          </el-form-item>
          <el-form-item label="延后自提" prop="delay">
            <el-radio-group v-model="subForm.delay">
              <el-radio :label="0">
                <el-select
                  v-model="subForm.delay_time"
                  filterable
                  clearable
                  placeholder="请选择"
                  style="width: 150px"
                >
                  <el-option
                    v-for="item in delayTimeOptions"
                    :key="item.key"
                    :label="item.label"
                    :value="item.key"
                  ></el-option>
                </el-select>
                <block>小时</block>
                <lb-tool-tips
                  >用户下单时，至少x小时后才能去自提，此字段是为了给卖家预留准备商品的时间。</lb-tool-tips
                >
              </el-radio>
              <div class="space-md"></div>
              <el-radio :label="1">
                <el-select
                  v-model="subForm.delay_day"
                  filterable
                  clearable
                  placeholder="请选择"
                  style="width: 150px"
                >
                  <el-option
                    v-for="item in delayDayOptions"
                    :key="item.key"
                    :label="item.label"
                    :value="item.key"
                  ></el-option>
                </el-select>
                <block>天</block>
                <lb-tool-tips
                  >为自然天，如：设置1天，买家只能预约1天后自提。</lb-tool-tips
                >
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="最长预约" prop="max_day">
            可预约
            <el-select
              v-model="subForm.max_day"
              filterable
              clearable
              placeholder="请选择"
              style="width: 150px"
            >
              <el-option
                v-for="item in maxDayOptions"
                :key="item.key"
                :label="item.label"
                :value="item.key"
              ></el-option>
            </el-select>
            天内订单
            <lb-tool-tips
              >例如：可预约7天内订单，自然天近7天内的时间都可以选择</lb-tool-tips
            >
          </el-form-item>
        </div>
        <el-form-item label="自提点照片" prop="img">
          <lb-cover
            type="more"
            :fileList="subForm.img"
            :fileSize="6"
            @selectedFiles="selectedFiles($event, 'img')"
            @moveFiles="moveFiles($event, 'img')"
          ></lb-cover>
          <lb-tool-tips>图片建议尺寸：750 * n，不超过6张图片</lb-tool-tips>
        </el-form-item>
        <el-form-item label="备注信息" prop="text">
          <el-input
            type="textarea"
            :rows="7"
            v-model="subForm.text"
            maxlength="200"
            resize="none"
            show-word-limit
            placeholder="可以描述自提点的活动或者其他信息"
          ></el-input>
        </el-form-item>

        <el-form-item>
          <lb-button @click="submitFormInfo" type="primary">{{
            $t('action.submit')
          }}</lb-button>
          <lb-button @click="goBack" v-if="id">{{
            $t('action.back')
          }}</lb-button>
        </el-form-item>
      </el-form>
    </div>

    <lb-map :dialogVisible.sync="showMap" @selectedLatLng="getLatLng"></lb-map>
    <el-dialog
      title="买家自提时间选择示例"
      :visible.sync="showDialog"
      width="600px"
      center
    >
      <div class="dialog-inner">
        <div class="flex-center">例如：自提时间为：14:00 - 22:00</div>
        <div class="flex-between pt-lg">
          <div class="mr-lg">
            <div class="flex-center mb-md">按半小时细分</div>
            <lb-image
              src=""
            />
          </div>
          <div class="ml-lg">
            <div class="flex-center mb-md">按一小时细分</div>
            <lb-image
              src=""
            />
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="showDialog = false">知道了</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { regionData } from 'element-china-area-data'
export default {
  data () {
    let validateCompany = (rule, value, callback) => {
      if (this.subForm.public_company === 0 && this.subForm.company.length < 1) {
        callback(new Error('请选择公司'))
      } else {
        callback()
      }
    }
    return {
      showMap: false,
      image:
        'https://longbing.oss-cn-beijing.aliyuncs.com/testing/image/8895/20/06/7100304eb06411ea98f2a1ce3cdd5154.png',
      showDialog: false,
      areaOptions: regionData,
      navTitle: '',
      loading: false,
      checkList: ['工作日（周一至周五）', '非工作日（周六至周日）'],
      authList: [
        {
          title: '工作日（周一至周五）',
          key: 'work'
        },
        {
          title: '非工作日（周六至周日）',
          key: 'no_work'
        }
      ],
      delayTimeOptions: [{ label: `0.5`, key: 0.5 * 60 }],
      delayDayOptions: [],
      maxDayOptions: [],
      // 基本信息
      options: {},
      copyCompanyId: [],
      companyResult: { company: [] },
      subForm: {
        title: '',
        company: [],
        public_company: 1,
        province: '',
        city: '',
        area: '',
        province_code: '',
        city_code: '',
        area_code: '',
        address: '',
        longitude: '',
        latitude: '',
        mobile: '',
        reception_time: 1, // 接待时间（0：全天,1:自定义）
        work: 1, // 工作日
        no_work: 1, // 非工作日
        work_start_time: '',
        work_end_time: '',
        no_work_start_time: '',
        no_work_end_time: '',
        is_self: 1, // 需要买家选择自提时间
        time_slot: 0, // 细分时段
        delay: 0, // 延后自提
        delay_time: '', // 延后自提时间
        delay_day: '', // 延后自提天数
        max_day: '', // 最长预约
        img: [],
        text: '' // 备注
      },
      subFormRules: {
        title: {
          required: true,
          type: 'string',
          message: '请输入标题',
          trigger: 'blur'
        },
        public_company: {
          required: true
        },
        company: {
          required: true,
          validator: validateCompany,
          trigger: 'blur'
        },
        address: {
          required: true,
          type: 'string',
          message: '请输入详细地址',
          trigger: 'blur'
        },
        longitude: {
          required: true,
          message: '请输入自提点经度',
          trigger: ['blur', 'change']
        },
        latitude: {
          required: true,
          message: '请输入自提点纬度',
          trigger: ['blur', 'change']
        },
        reception_time: {
          required: true,
          type: 'number',
          message: '请选择接待时间',
          trigger: 'change'
        },
        is_self: {
          required: true,
          type: 'number',
          message: '请选择自提时间',
          trigger: 'change'
        },
        time_slot: {
          required: true,
          type: 'number',
          message: '请选择细分时段',
          trigger: 'change'
        },
        delay: {
          required: true,
          type: 'number',
          message: '请选择延后自提',
          trigger: 'change'
        },
        max_day: {
          required: true,
          type: 'number',
          message: '请选最长预约时间',
          trigger: 'change'
        },
        img: {
          required: true,
          type: 'array',
          message: '请上传图片',
          trigger: 'change'
        }
      },
      phoneForm: {
        phoneCode: '',
        phone: ''
      },
      phoneFormRules: {
        phone: {
          required: true,
          type: 'string',
          message: '请输入联系电话',
          trigger: 'blur'
        }
      },
      areaForm: {
        selectedOptions: []
      },
      areaFormRules: {
        selectedOptions: {
          required: true,
          type: 'array',
          message: '请选择自提地址',
          trigger: 'change'
        }
      }
    }
  },
  async created () {
    let { id } = this.$route.query
    await this.getSelectOptions()
    if (id) {
      this.id = id
      await this.getDetail(id)
    }
    this.navTitle = this.$t(id ? 'menu.StoreEdit' : 'menu.StoreAdd')
    for (let i = 1; i < 91; i++) {
      if (i < 31) {
        this.delayDayOptions.push({ label: `${i}`, key: i })
      }
      if (i < 49) {
        this.delayTimeOptions.push({ label: `${i}`, key: i * 60 })
      }
      this.maxDayOptions.push({ label: `${i}`, key: i })
    }
  },
  methods: {
    getSelectOptions () {
      this.$api.GoodsListSelectV2().then(res => {
        if (res.code === 200) {
          let { data } = res
          this.handleCompanyOptions(data.company, [], 'company')
          // data.company.length && data.company.unshift({
          //   id: 0,
          //   name: '全选'
          // })
          this.options = data
        }
      })
    },
    handleCompanyOptions (data, arr = [], key) {
      for (let i = 0, len = data.length; i < len; i++) {
        let newArr = JSON.parse(JSON.stringify(arr))
        newArr.push(data[i].id)
        this.companyResult[key].push(JSON.parse(JSON.stringify(newArr)))
        if (data[i].children && data[i].children.length > 0) {
          this.handleCompanyOptions(data[i].children, newArr, key)
        }
      }
    },
    async getDetail (id) {
      let { code, data } = await this.$api.storeInfo({ id })
      if (code !== 200) return
      this.copyCompanyId = data.company
      if (data.delay_time === 0) {
        data.delay_time = ''
      }
      if (data.delay_day === 0) {
        data.delay_day = ''
      }
      this.subForm = data
      this.subForm.img = data.img.map(item => {
        return {
          url: item
        }
      })
      let checkItem = []
      this.authList.map(item => {
        if (data[item.key] === 1) {
          checkItem.push(item.title)
        }
      })
      this.checkList = checkItem
      let selectedOptions = [data.province_code]
      if (data.city_code) {
        selectedOptions.push(data.city_code)
      }
      if (data.area_code) {
        selectedOptions.push(data.area_code)
      }
      this.areaForm.selectedOptions = selectedOptions

      if (data.mobile.includes(' - ')) {
        let arr = data.mobile.split(' - ')
        this.phoneForm.phoneCode = arr[0]
        this.phoneForm.phone = arr[1]
      } else {
        this.phoneForm.phone = data.mobile
      }
    },
    handleChange (e) {
      this.subForm.province_code = e[0] || ''
      this.subForm.city_code = e[1] || ''
      this.subForm.area_code = e[2] || ''
      this.subForm.province = ''
      this.subForm.city = ''
      this.subForm.area = ''
      regionData.map((item, index) => {
        if (item.value === e[0]) {
          this.subForm.province = item.label
          if (item.children && item.children.length > 0) {
            item.children.map(aitem => {
              if (aitem.value === e[1]) {
                this.subForm.city = aitem.label
                if (aitem.children && aitem.children.length > 0) {
                  aitem.children.map(bitem => {
                    if (bitem.value === e[2]) {
                      this.subForm.area = bitem.label
                    }
                  })
                }
              }
            })
          }
        }
      })
    },
    changeCheckBox (e) {
      this.authList.map(item => {
        this.subForm[item.key] = e.includes(item.title) ? 1 : 0
      })
    },
    /**
     * @method 获取经纬度
     */
    getLatLng (latLng) {
      this.subForm.latitude = latLng.lat
      this.subForm.longitude = latLng.lng
    },
    selectedFiles (imgs, key) {
      this.subForm[key].push(...imgs)
    },
    moveFiles (imgs, key) {
      this.subForm[key] = imgs
    },
    handleMomentTime (time) {
      return new Date(time * 1000)
    },
    handleTimes (time) {
      return parseInt(new Date(time).getTime() / 1000)
    },
    goBack () {
      this.$router.back(-1)
    },
    async submitFormInfo () {
      let subForm = JSON.parse(JSON.stringify(this.subForm))
      let formArr = ['aForm', 'bForm', 'cForm', 'dForm']
      let flag = true
      for (let i = 0, len = formArr.length; i < len; i++) {
        this.$refs[formArr[i]].validate(valid => {
          if (!valid) {
            flag = false
            return false
          }
        })
      }
      if (flag) {
        let { phoneCode, phone } = this.phoneForm
        subForm.mobile = phoneCode ? `${phoneCode} - ${phone}` : phone
        subForm.img = subForm.img.map(item => {
          return item.url
        })

        if (subForm.reception_time === 0 || (subForm.reception_time === 1 && subForm.work === 0)) {
          subForm.work = 0
          subForm.work_start_time = ''
          subForm.work_end_time = ''
        }
        if (subForm.reception_time === 0 || (subForm.reception_time === 1 && subForm.no_work === 0)) {
          subForm.no_work = 0
          subForm.no_work_start_time = ''
          subForm.no_work_end_time = ''
        }

        if (subForm.reception_time === 1 && subForm.work === 0 && subForm.no_work === 0) {
          this.$message.error('请选择接待时间')
          return
        }

        let isWorkCheck = subForm.reception_time === 1 && subForm.work === 1
        if (
          (isWorkCheck && !subForm.work_start_time) ||
          (isWorkCheck && !subForm.work_end_time)
        ) {
          this.$message.error('请选择工作日接待时间')
          return
        }
        let isNoWorkCheck = subForm.reception_time === 1 && subForm.no_work === 1
        if (
          (isNoWorkCheck && !subForm.no_work_start_time) ||
          (isNoWorkCheck && !subForm.no_work_end_time)
        ) {
          this.$message.error('请选择非工作日接待时间')
          return
        }

        if ((subForm.is_self === 1 && subForm.delay === 0 && !subForm.delay_time) || (subForm.is_self === 1 && subForm.delay === 1 && !subForm.delay_day)) {
          let delayMsg = subForm.delay === 0 ? '请选择延后自提时间' : '请选择延后自提天数'
          this.$message.error(delayMsg)
          return
        }

        let methodModel = subForm.id ? 'storeUpdate' : 'storeAdd'
        let { code } = await this.$api[methodModel](subForm)
        if (code !== 200) return
        this.$message.success(this.$t('tips.successSub'))
        this.goBack()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.lb-edit-card {
  width: 100%;
  .el-input,
  .el-select,
  .lb-input-number,
  .el-cascader {
    width: 400px;
  }
  .el-textarea {
    width: 600px;
  }
  .el-image {
    border-radius: 10px;
    border: 1px solid #909399;
  }
  .inline-form {
    width: 900px;
    padding-left: 40px;
    .el-input,
    .el-input-number {
      width: 200px;
    }
    .getLocation {
      margin-top: 5px;
    }
  }
}
</style>
